/**
 * 解析时间到字符串
 * @param time {(Date | string | number)} 时间
 * @param cFormat {string} 格式化字符串
 * @returns {string | null}
 */
export function parseTime(time: Date | string | number | null, cFormat?: string): string | null {
  if (!time) {
    return null;
  }

  const format: string = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date: Date;

  if (time instanceof Date) {
    date = time;
  } else {
    if (typeof time === "string") {
      if (/^[0-9]+$/.test(time)) {
        // 支持 "1548221490638"
        time = parseInt(time, 10);
      } else {
        // 支持 Safari
        time = time.replace(new RegExp("/", "g"), "-");
      }
    }

    if (typeof time === "number" && time.toString().length === 10) {
      time *= 1000;
    }
    date = new Date(time);
  }

  if (isNaN(date.getTime())) {
    return null;
  }

  const formatObj: { [key: string]: number | string } = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };

  return format.replace(new RegExp("{([ymdhisa])+}", "g"), (result, key) => {
    const value = formatObj[key];
    // 注意：getDay（） 在星期日返回 0
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value as number];
    }
    return value.toString().padStart(2, "0");
  });
}
export default parseTime;
